package com.kfm.company.interceptor;

import com.kfm.company.model.bean.IPInfo;
import com.kfm.company.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登录请求的次数
 */
@Component
public class LoginCountInterceptor implements HandlerInterceptor {
    @Autowired
    private IPInfo ipInfo;

    @Value("${wx.login_count}")
    private Integer max;

    @Autowired
    private AccessIPInterceptor accessIPInterceptor;


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user != null) { // 登录成功，清空IP的计次
            String ip = IPUtil.getIpAddress(request);
            ipInfo.getIpMap().put(ip, null); // 将ip原有的计次清空
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("get".equalsIgnoreCase(method)) {
            return true;
        }
        Map<String, Integer> ipMap = ipInfo.getIpMap();
        // 获取IP地址
        String ip = IPUtil.getIpAddress(request);
        Integer count = ipMap.get(ip);
        if (count == null) {
            // 第一次登录，直接放行，并存储到map集合中
            ipMap.put(ip, 1);
            return true;
        } else {
            count = count + 1;
            if (count >= max) {
                // 禁止访问网站任何的地方
                accessIPInterceptor.blackIPList.add(ip);
                response.sendRedirect(request.getContextPath() + "/error");
                return false;
            } else {
                ipMap.put(ip, count);
                return true;
            }
        }
    }
}
